package comment

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	"google.golang.org/grpc/codes"
	"gorm.io/gorm"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeletePostCommentLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeletePostCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeletePostCommentLogic {
	return &DeletePostCommentLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// getAllChildCommentIds 使用SQL递归CTE一次性查询所有子评论ID
func (l *DeletePostCommentLogic) getAllChildCommentIds(commentId int64) ([]int64, error) {
	var commentIds []int64

	// MySQL递归CTE查询所有子评论
	sql := `
	WITH RECURSIVE comment_tree AS (
		-- 起始条件：选择当前评论
		SELECT id FROM cs_community_post_comment WHERE id = ?
		UNION ALL
		-- 递归条件：查找子评论
		SELECT c.id FROM cs_community_post_comment c
		INNER JOIN comment_tree ct ON c.pid = ct.id
	)
	SELECT id FROM comment_tree`

	if err := l.svcCtx.DB.WithContext(l.ctx).Raw(sql, commentId).Scan(&commentIds).Error; err != nil {
		return nil, err
	}

	return commentIds, nil
}

func (l *DeletePostCommentLogic) DeletePostComment(req *types.PostCommentDeleteReq) (resp *types.Empty, err error) {
	// 检查评论是否存在
	var existComment model.CsCommunityPostComment
	if err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPostComment{}).
		Where("id = ?", req.Id).Find(&existComment).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if existComment.ID == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.CommentNotFound)
	}

	// 递归获取所有需要删除的评论ID（包括子评论）
	allCommentIds, err := l.getAllChildCommentIds(req.Id)
	if err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	// 开始事务
	err = l.svcCtx.DB.WithContext(l.ctx).Transaction(func(tx *gorm.DB) error {
		// 删除所有相关的点赞记录
		if err := tx.Model(&model.CsCommunityPostCommentApprove{}).
			Where("comment_id IN ?", allCommentIds).Delete(&model.CsCommunityPostCommentApprove{}).Error; err != nil {
			return err
		}

		// 删除所有评论（包括子评论）
		if err := tx.Model(&model.CsCommunityPostComment{}).
			Where("id IN ?", allCommentIds).Delete(&model.CsCommunityPostComment{}).Error; err != nil {
			return err
		}

		return nil
	})

	if err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	return &types.Empty{}, nil
}
